package com.csg.ses.common.utils;

import java.io.*;
import java.lang.reflect.Field;

/**
 * 通用工具类
 * @auther wangjun
 * @date 2020/11/16
 */
public class CommonUtil {
    /**
     * 判断是否为空
     * @param val
     * @return
     */
    public static Boolean isEmpty(String val) {
        return (val == null || "null".equals(val)) ? true : (val.length() == 0);
    }

    /**
     * 文件转数组
     * @param filePath
     * @return
     */
    public static byte[] getBytes(String filePath) {
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000000);  	//字节
            byte[] b = new byte[1000000];  //字节数组
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    /**
     * 删除文件
     * @param filePath
     */
    public static void deleteTmpFile(String filePath) {
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        }
    }

    /**
     * 将一个实体类复制到另一个实体类中
     * @param fromBean
     * @param toBean
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     * @throws Exception
     */
    public static void copySameBean(Object fromBean, Object toBean) throws NullPointerException, IllegalArgumentException, IllegalAccessException {
        if(fromBean == toBean) {
            return;
        }
        if(fromBean != null) {
            // 得到类对象
            Class fromBeanClass = (Class) fromBean.getClass();
            Class toBeanClass = (Class) toBean.getClass();

            /**
             * 得到类中的所有属性集合
             */
            Field[] fbc = fromBeanClass.getDeclaredFields();
            Field[] tbc = toBeanClass.getDeclaredFields();
            for(int i = 0;i < fbc.length;i++) {
                Field f = fbc[i];
                f.setAccessible(true); // 设置些属性是可以访问的
                Object fVal = f.get(fromBean);// 得到此属性的值
                //System.out.println("name:" + f.getName() + "\t value = " + fVal);
                for(int j = 0;j < tbc.length;j++) {
                    Field t = tbc[i];
                    t.setAccessible(true); // 设置些属性是可以访问的
                    // 属性名称和属性类型必须全部相同，才能赋值
                    if(f.getName().equals(t.getName()) && f.getType().toString().equals(t.getType().toString())){
                        t.set(toBean, fVal);
                    }
                }
            }
        } else {
            throw new NullPointerException("FromBean is null");
        }
    }
}